<?php

/**
 * Created by PhpStorm.
 * Script Name: Minisetting.php
 * Create: 2023/02/04 下午10:16
 * Description: 小程序相关设置
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\admin\controller;

use app\common\model\App as AppM;
use app\common\model\AppInfo as AppInfoM;
use plugin\wechat\app\AdminController;
use plugin\wechat\app\service\MiniTemplateApp as TemplateAppService;
use plugin\wechat\app\model\MiniTemplateLog as TemplateLogM;
use plugin\wechat\app\service\MiniTemplate as TemplateService;
use Support\Request;
use app\common\service\App as AppService;

class Minisetting extends AdminController
{
    /**
     * @var AppInfoM
     */
    protected $appInfoM;

    /**
     * @var TemplateLogM
     */
    private TemplateLogM $templateM;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new AppM();
        $this->appInfoM = new AppInfoM();

        $this->templateM = new TemplateLogM();
    }

    private static function tabList($id = 0){
        return [
            'domains' => [
                'title' => '开发/业务域名',
                'href' => url('config', ['name' => 'domains', 'id' => $id])
            ],
            'privacy' => [
                'title' => '隐私保护指引',
                'href' => url('config', ['name' => 'privacy', 'id' => $id])
            ],
            'extjson' => [
                'title' => 'extJson参数',
                'href' => url('config', ['name' => 'extjson', 'id' => $id])
            ]
        ];
    }

    public function index(){
        if(request()->isPost()){
            $post_data = input('post.');
            $where = [
                ['type', 'like', "%mini%"],
                ['name', '<>', 'wechat']
            ];
            !empty($post_data['search_key']) && $where[] = ['title|name', 'like', '%'.$post_data['search_key'].'%'];
            $query = $this->model->where($where);
            $total = $query->count();
            if($total){
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('id', 'desc')
                    ->select();
            }else{
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '搜索词','placeholder' => '应用名称或标识']
        ])
            ->addTableColumn(['title' => 'logo', 'field' => 'logo', 'type' => 'picture'])
            ->addTableColumn(['title' => '标识', 'field' => 'name'])
            ->addTableColumn(['title' => '名称', 'field' => 'title'])
            ->addTableColumn(['title' => '版本', 'field' => 'version'])
            ->addTableColumn(['title' => '状态', 'field' => 'status', 'type' => 'switch', 'text' => '上架|下架'])
            ->addTableColumn(['title' => '操作', 'width' => 170, 'type' => 'toolbar'])
            ->addRightButton('edit', ['text' => '开发配置', 'href' => url('config', ['id' => '__data_id__'])])
            ->addRightButton('edit', ['text' => '设置模版', 'href' => url('setTemplate', ['id' => '__data_id__'])]);
        return $builder->show();
    }

    /**
     * 设置模版
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function setTemplate(){
        if(request()->isPost()){
            $post_data = input('post.');
            $mini_template = TemplateAppService::updateByApp($post_data['app_name'], $post_data['template_id']);
            return $this->success('设置成功');
        }

        if(! $app = AppService::getAppInfo(input('id', 0))){
            return $this->error('数据不存在');
        }

        $templates = TemplateService::getDictList();
        $mini_template = TemplateAppService::getByApp($app['name']);
        if(! $mini_template){
            $mini_template = [
                'app_name' => $app['name'],
                'cur_temp' => '未设置'
            ];
        }else{
            $mini_template['cur_temp'] = $templates[$mini_template['template_id']] ?? '';
        }

        $builder = new FormBuilder();
        $builder->addFormItem('app_name', 'hidden', 'addon', 'addon')
            ->addFormItem('title', 'static', '应用',$app['title'])
            ->addFormItem('cur_temp', 'static', '当前模版', $mini_template['cur_temp'])
            ->addFormItem('template_id', 'chosen', '选择模版', '选择模版', $templates, 'required')
            ->setFormData($mini_template);
        return $builder->show();
    }

    /**
     * 设置
     * @param Request $request
     * @return mixed
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author: fudaoji<fdj@kuryun.cn>
     */
    public function config(Request $request){
        if(! $app = AppService::getAppInfo(input('id', 0))){
            return $this->error('数据不存在');
        }

        $current_name = input('name', 'domains');
        $config = empty($app['config']) ? [] : json_decode($app['config'], true);
        $data = empty($config[$current_name]) ? [] : $config[$current_name];

        $builder = new FormBuilder();
        switch ($current_name){
            case 'extjson':
                $data = ['extjson' => $data ?: ''];
                $builder->addFormItem('extjson', 'textarea', 'extJson', '一行一对配置，例如：
restUrl|http://demo.com
appKey|123456');
                break;
            case 'privacy':
                $builder->addFormItem('privacy', 'legend', '用户隐私设置', '用户隐私保护指引参数设置')
                    ->addFormItem('contact_phone', 'number', '开发者手机号', '请填写真实手机号',[], 'required')
                    ->addFormItem('notice_method', 'text', '通知方式', '指的是当开发者收集信息有变动时，通过该方式通知用户。这里服务商需要按照实际情况填写，例如通过弹窗或者公告或者其他方式',[], 'required')
                    ->addFormItem('setting_list', 'textarea', '要收集的信息', '一行一对配置，例如：
UserInfo|个人中心显示个人信息
Location|提供最近的服务')
                    ->addFormItem('privacy_ver', 'radio', '更新版本', '更新版本',[1 => '现网版本', 2 => '开发版本'], 'required');
                break;
            case 'domains':
                $builder->addFormItem('domains', 'legend', '服务器域名', '服务器域名')
                    ->addFormItem('request_domain', 'textarea', 'request合法域名', '多个域名使用;隔开')
                    ->addFormItem('socket_domain', 'textarea', 'socket合法域名', '多个域名使用;隔开')
                    ->addFormItem('upload_domain', 'textarea', 'uploadFile合法域名', '多个域名使用;隔开')
                    ->addFormItem('download_domain', 'textarea', 'downloadFile合法域名', '多个域名使用;隔开')
                    ->addFormItem('udp_domain', 'textarea', 'udp合法域名', '多个域名使用;隔开')
                    ->addFormItem('tcp_domain', 'textarea', 'tcp合法域名', '多个域名使用;隔开')
                    ->addFormItem('webview', 'legend', '业务域名', '业务域名')
                    ->addFormItem('webview_domain', 'textarea', '业务域名', '多个域名使用;隔开');
                break;
        }
        $builder->setTabNav($this->tabList($app['id']), $current_name)
            ->setPostUrl(url('savePost', ['name' => $current_name, 'id' => $app['id']]))
            ->setFormData($data);
        return $builder->show();

    }

    public function savePost(Request $request, $jump = '', $data = []){
        if(! $app = AppService::getAppInfo(input('id', 0))){
            return $this->error('数据不存在');
        }
        $post_data = input('post.');
        unset($post_data['__token__']);
        $current_name = input('name', 'domains');
        $data = empty($app['config']) ? [] : json_decode($app['config'], true);
        $data[$current_name] = $post_data;
        if($current_name == 'extjson'){
            $data['extjson'] = $post_data['extjson'];
        }
        AppService::updateInfo(['id' => $app['id'], 'config' => $data]);
        return $this->success('操作成功！', url('config', ['name' => $current_name, 'id' => $app['id']]));
    }
}
